package com.example.health.service.impl;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.health.common.Result;
import com.example.health.entity.CheckFiles;
import com.example.health.entity.User;
import com.example.health.mapper.CheckFilesMapper;
import com.example.health.mapper.CheckGroupMapper;
import com.example.health.mapper.CheckSetMealMapper;
import com.example.health.mapper.UserMapper;
import com.example.health.service.CheckFilesService;
import com.example.health.utils.NumberFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class CheckFilesServiceImpl extends ServiceImpl<CheckFilesMapper, CheckFiles> implements CheckFilesService {

    @Resource
    private CheckFilesMapper checkFilesMapper;
    @Resource
    private UserMapper userMapper;


    /**
     * 查询健康档案文件列表
     * @param pageNum
     * @param pageSize
     * @param search
     * @param userId
     * @return
     */
    @Override
    public Result<?> findCheckFilesPage(Integer pageNum, Integer pageSize, String search, Integer userId) {
        LambdaQueryWrapper<CheckFiles> wrapper = Wrappers.<CheckFiles>lambdaQuery();//创建查询条件
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(CheckFiles::getUserName, search);
        }
        wrapper.eq(CheckFiles::getIsDel, 0);
        if (userId != null) {
            wrapper.eq(CheckFiles::getUserId, userId);
        }
        Page<CheckFiles> newsPage = checkFilesMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(newsPage);
    }

    /**
     * 添加健康档案文件
     * @param checkFiles
     * @return
     */
    @Override
    public Result<?> addCheckFiles(CheckFiles checkFiles) {
        // 数据验证
        if (checkFiles.getUserId() == null) {
            return Result.error("-1", "用户ID不能为空");
        }

        // 检查用户是否存在
        User user = userMapper.selectById(checkFiles.getUserId());
        if (user == null) {
            return Result.error("-1", "用户不存在");
        }

        // 检查身份证号是否合法（如果提供了）
        if (StrUtil.isNotBlank(checkFiles.getCardNumber())) {
            // 使用正则表达式验证身份证号格式
            String cardNumber = checkFiles.getCardNumber();
            if (!IdcardUtil.isValidCard(cardNumber)) {
                return Result.error("-1", "身份证号码格式不正确");
            }
        }

        // 检查手机号是否合法（如果提供了）
        if (StrUtil.isNotBlank(checkFiles.getPhone())) {
            String phone = checkFiles.getPhone();
            if (!ReUtil.isMatch("^1[3-9]\\d{9}$", phone)) {
                return Result.error("-1", "手机号格式不正确");
            }
        }

        // 检查是否已经存在该用户的健康档案
        LambdaQueryWrapper<CheckFiles> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(CheckFiles::getUserId, checkFiles.getUserId());
        queryWrapper.eq(CheckFiles::getIsDel, 0);
        CheckFiles existingFiles = checkFilesMapper.selectOne(queryWrapper);
        if (existingFiles != null) {
            return Result.error("-1", "该用户已存在健康档案，请勿重复添加");
        }

        // 设置创建时间和更新时间
        checkFiles.setCreateTime(new Date());
        checkFiles.setUpdateTime(new Date());
        checkFiles.setIsDel(0);

        // 插入数据
        checkFilesMapper.insert(checkFiles);
        return Result.success();
    }

    /**
     * 修改健康档案文件
     * @param checkFiles
     * @return
     */
    @Override
    public Result<?> update(CheckFiles checkFiles) {
        if (checkFiles.getId() == null) {
            return Result.error("-1", "健康档案ID不能为空");
        }
        // 检查健康档案是否存在
        CheckFiles existingFiles = checkFilesMapper.selectById(checkFiles.getId());
        if (existingFiles == null || existingFiles.getIsDel() == 1) {
            return Result.error("-1", "健康档案不存在");
        }
        // 检查身份证号是否合法（如果提供了）
        if (StrUtil.isNotBlank(checkFiles.getCardNumber())) {
            String cardNumber = checkFiles.getCardNumber();
            if (!IdcardUtil.isValidCard(cardNumber)) {
                return Result.error("-1", "身份证号码格式不正确");
            }
        }

        // 检查手机号是否合法（如果提供了）
        if (StrUtil.isNotBlank(checkFiles.getPhone())) {
            String phone = checkFiles.getPhone();
            if (!ReUtil.isMatch("^1[3-9]\\d{9}$", phone)) {
                return Result.error("-1", "手机号格式不正确");
            }
        }

        // 设置更新时间
        checkFiles.setUpdateTime(new Date());
        checkFilesMapper.updateById(checkFiles);
        return Result.success();
    }

    @Override
    public Result<?> delete(Integer id) {
        CheckFiles checkFiles = new CheckFiles();
        checkFiles.setId(id);
        checkFiles.setIsDel(1);
        checkFiles.setUpdateTime(new Date());
        checkFilesMapper.updateById(checkFiles);
        return Result.success();
    }

    @Override
    public Result<?> getMealList(CheckFiles checkFiles) {
        LambdaQueryWrapper<CheckFiles> wrapper = Wrappers.<CheckFiles>lambdaQuery();
        if (checkFiles.getUserId() != null) {
            wrapper.eq(CheckFiles::getUserId, checkFiles.getUserId());
        }
        wrapper.eq(CheckFiles::getIsDel, 0);
        List<CheckFiles> list = checkFilesMapper.selectList(wrapper);
        return Result.success(list);
    }
}
